package com.cvit.controller;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import com.cvit.model.Examinationtable;
import com.cvit.model.Msg;
import com.cvit.model.Student;
import com.cvit.model.Time;
import com.cvit.service.ExaminationtableService;
import com.cvit.service.StudentService;
import com.cvit.service.TimeService;
import com.cvit.utils.FileUpload;
import com.cvit.utils.Utils;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;

import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import sun.misc.BASE64Encoder;

@Controller
public class ExaminationtableController {
	@Autowired
	ExaminationtableService examinationtableService;
	@Autowired
	StudentService studentService;
	@Autowired
	TimeService timeservice;

	private Configuration configuration = null;

	@SuppressWarnings("deprecation")
	public ExaminationtableController() {
		configuration = new Configuration();
		configuration.setDefaultEncoding("utf-8");
	}

	/**
	 * 查询所有准考证信息
	 */
	@RequestMapping("/selectTicketAll")
	@ResponseBody
	public Msg getStudents(@RequestParam(value = "pn", defaultValue = "1") Integer pn) {
		PageHelper.startPage(pn, 5);
		List<Examinationtable> examinationtable = examinationtableService.selectTicketAll();
		PageInfo<Examinationtable> page = new PageInfo<Examinationtable>(examinationtable, 5);
		return Msg.success().add("pageInfo", page);
	}

	/**
	 * 按学生号、身份证号查询准考证信息 Ws
	 */
	@ResponseBody
	@RequestMapping("/selectTicket")
	public Msg selectTicket(Examinationtable eamineeId) {
		Date day=new Date();
		SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHH");
		long ts1= Long.parseLong(df.format(day));
		long ts2 = 2018031507; 
		long timeEnd = 2018031717;
		if(ts1>ts2){
			if(ts1<timeEnd){
				if(eamineeId.getEamineeId().length()==18){
					eamineeId.setCardId(eamineeId.getEamineeId());
				}
				if(eamineeId.getCardId()==null || eamineeId.getCardId()==""){
					List<Examinationtable> ticket = examinationtableService.getEamineeId(eamineeId);
					if(ticket.size()==0){
						return Msg.fail().add("code", "该考生未参加缴费报名考试");
					}else{
						return Msg.success().add("Ticket", ticket);
					}
				}else{
					List<Examinationtable> ticket1 = examinationtableService.getCardId(eamineeId);
					if(ticket1.size()==0){
						return Msg.fail().add("code", "该考生未参加缴费报名考试");
					}else{
						return Msg.success().add("Ticket", ticket1);
					}
				}
			}else{
				return Msg.fail().add("code", "打印准考证已结束");
			}
		}else{
			return Msg.fail().add("code", "打印准考证还未开放");
		}
		
	}
	

	/**
	 * 生成Word文档准考证
	 * 
	 * @throws IOException
	 * @throws FileNotFoundException
	 */
	@ResponseBody
	@RequestMapping("/eamineedoc")
	public Msg createDoc(Examinationtable examinationtable, HttpServletRequest request, HttpServletResponse response)
			throws FileNotFoundException, IOException {
			Student student = studentService.getStudnetByEamineeId(examinationtable.getEamineeId());
			System.out.println(student);
			if (Utils.isNull(student) == false) {
				String dir = request.getSession().getServletContext().getRealPath("/");// 总路径
				String ticketPath = "Ticket/";
				String ticketFilePath = dir + ticketPath;
				if (student.getTicketType() == 2) {
					List<Examinationtable> getUserDoc = examinationtableService.getEamineeId(examinationtable);
					Map map = new HashMap();
					if (getUserDoc.size() == 1) {
						map.put("image", getimg(request, getUserDoc.get(0).getEamineeId()));
						map.put("name", getUserDoc.get(0).getName());
						map.put("gender", getUserDoc.get(0).getGender());
						map.put("student_number", getUserDoc.get(0).getStudentNumber());
						map.put("eaminee_id", getUserDoc.get(0).getEamineeId());
						map.put("card_id", getUserDoc.get(0).getCardId());
						map.put("examine_number", getUserDoc.get(0).getExamineNumber());
						map.put("examination_time0", getUserDoc.get(0).getExaminationTime());
						map.put("overall0", getUserDoc.get(0).getOverall());
						map.put("examination_place0", getUserDoc.get(0).getExaminationPlace());
						map.put("examination_room0", getUserDoc.get(0).getExaminationRoom());
						map.put("test_time0", getUserDoc.get(0).getTestTime());
					} else {
						map.put("image", getimg(request, getUserDoc.get(0).getEamineeId()));
						map.put("name", getUserDoc.get(0).getName());
						map.put("gender", getUserDoc.get(0).getGender());
						map.put("student_number", getUserDoc.get(0).getStudentNumber());
						map.put("eaminee_id", getUserDoc.get(0).getEamineeId());
						map.put("card_id", getUserDoc.get(0).getCardId());
						map.put("examine_number", getUserDoc.get(0).getExamineNumber());
						map.put("examination_time0", getUserDoc.get(0).getExaminationTime());
						map.put("examination_time1", getUserDoc.get(1).getExaminationTime());
						map.put("overall0", getUserDoc.get(0).getOverall());
						map.put("overall1", getUserDoc.get(1).getOverall());
						map.put("examination_place0", getUserDoc.get(0).getExaminationPlace());
						map.put("examination_place1", getUserDoc.get(1).getExaminationPlace());
						map.put("examination_room0", getUserDoc.get(0).getExaminationRoom());
						map.put("examination_room1", getUserDoc.get(1).getExaminationRoom());
						map.put("test_time0", getUserDoc.get(0).getTestTime());
						map.put("test_time1", getUserDoc.get(1).getTestTime());
					}
					configuration.setClassForTemplateLoading(this.getClass(), "/com/cvit/utils");
					Template t = null;
					try {
						// test.ftl为要装载的模板
						t = configuration.getTemplate("examination.ftl");
						t.setEncoding("utf-8");
					} catch (IOException e) {
						e.printStackTrace();
					}
					File ticketFile = new File(ticketFilePath);
					if (!ticketFile.exists()) {
						ticketFile.mkdirs();
					}
					// 输出文档路径及名称
					File outFile = new File(ticketFilePath, examinationtable.getEamineeId() + ".doc");
					Writer out = null;
					try {
						out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outFile), "utf-8"));
					} catch (Exception e1) {
						e1.printStackTrace();
					}
					try {
						t.process(map, out);
						out.close();
					} catch (TemplateException e) {
						e.printStackTrace();
					} catch (IOException e) {
						e.printStackTrace();
					}
					// 修改打印状态值
					studentService.updateTicketByEamineeId(examinationtable.getEamineeId());
				}
				//下载文件
				FileUpload.downloadTicketByOutputStream(response, request, ticketFilePath,
						examinationtable.getEamineeId());
				return Msg.success();
			} else {
				return Msg.fail().add("提示", "所输入的考生号不存在");
			}
	}

	private String getimg(HttpServletRequest request, String eamineeId) {
		String img_paths = "admissions_images/";
		String dir = request.getSession().getServletContext().getRealPath("/");// 总路径
		StringBuilder path = new StringBuilder(dir + img_paths);
		String imgPath = path + eamineeId + ".jpg";
		System.out.println("路径：" + imgPath);
		InputStream in = null;
		byte[] map = null;
		// 读取图片字节数组
		try {
			in = new FileInputStream(imgPath);
			map = new byte[in.available()];
			in.read(map);
			in.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
		BASE64Encoder encoder = new BASE64Encoder();
		return encoder.encode(map);// 返回Base64编码过的字节数组字符串
	}

	
	
	
	/**
	 * 查询考场表单（全部）
	 */
	@RequestMapping("/getExaminationtable")
	@ResponseBody
	public Msg getExaminationtable(@RequestParam(value = "pn", defaultValue = "1") Integer pn) {
		PageHelper.startPage(pn, 5);
		List<Examinationtable> examinationtable = examinationtableService.getExaminationtable();
		PageInfo<Examinationtable> page = new PageInfo<Examinationtable>(examinationtable, 5);
		return Msg.success().add("pageInfo", page);
	}

	/**
	 * 根据考生号(eaminee_id)、身份证号(card_id)、准考号(student_number)查询
	 */
	@RequestMapping("/getExaminationtableBy")
	@ResponseBody
	public Msg getExaminationtableBy(Examinationtable examinationtable) {
		List<Examinationtable> examinationtables = examinationtableService.getExaminationtableBy(examinationtable);
		return Msg.success().add("examinationtables", examinationtables);
	}

	/**
	 * 导入Excel
	 */
	@RequestMapping("/ExaminationtableImport")
	@ResponseBody
	public Msg impotr(HttpServletRequest request, Examinationtable examinationtable) throws Exception {
		// 获取上传的文件
		MultipartHttpServletRequest multipart = (MultipartHttpServletRequest) request;
		MultipartFile file = multipart.getFile("upfile");
		InputStream in = file.getInputStream();
		// 数据导入
		examinationtableService.importExcelInfo(in, file);
		in.close();
		return Msg.success();
	}

}
